package com.microcm.system.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;

import com.microcm.common.CUtils;
import com.microcm.common.Final;
import com.microcm.common.SystemToolkit;
import com.microcm.insync.service.InsyncService;
import com.microcmframework.core.BaseServlet;
import com.microcmframework.core.context.AppContext;
import com.microcmframework.core.entity.PageBean;

/**
 * 按宝贝、店铺、链接查询
 * 
 * @author kansum
 */
public class TopSearchListGoodsServlet extends BaseServlet
{
	private static final long serialVersionUID = 1L;

	private InsyncService insyncService;

	@Override
	public void init(ServletConfig cfg) throws ServletException
	{
		insyncService = (InsyncService) SystemToolkit.getBean("insyncService");
	}

	@Override
	protected void doProc(PrintWriter out, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
	{
		// 获得参数
		String unid = req.getParameter("unid");
		String searchType = req.getParameter("searchType");
		String keyword = new String(req.getParameter("q").getBytes("ISO-8859-1"), "UTF-8");

		// 关键词搜索
		if ("1".equals(searchType))
		{
			String s8Url = insyncService.getS8UrlFromTaobao(unid, keyword);
			// 跳转到结果页面，如果没有返回s8Url，那么使用本地查询
			if (CUtils.isEmpty(s8Url))
				resp.sendRedirect(AppContext.getInstance().getCtxurl() + "/svl/search?q=" + URLEncoder.encode(URLEncoder.encode(keyword, "UTF-8"), "UTF-8"));
			else
				resp.sendRedirect(s8Url);
		}

		// 店铺搜索
		else if ("2".equals(searchType))
		{
			// 先在index中搜索出店铺的sid
			String sids = queryShopIdsFromIndex(keyword);
			if (sids != null)
			{
				PageBean pageBean = new PageBean();
				String ret = this.insyncService.getConvertShopsFromTaobao(unid, sids, pageBean);
				if ("1".equals(ret))
				{
					// 设置值
					req.setAttribute("totalRecord", pageBean.getTotalRecord());
					req.setAttribute("shopList", pageBean.getRoot());
				}
			}
			req.getRequestDispatcher("/topSearchShopsList.jsp").forward(req, resp);
		}

		// 商品链接搜索
		else if ("3".equals(searchType))
		{
			String numIid = CUtils.getParamFromUrl(keyword, "id");
			req.setAttribute("totalRecord", 0);
			if (numIid != null)
			{
				PageBean pageBean = new PageBean();
				String ret = insyncService.getConvertGoodsFromTaobao(unid, numIid, pageBean);
				if ("1".equals(ret))
				{
					// 设置值
					req.setAttribute("totalRecord", pageBean.getTotalRecord());
					req.setAttribute("goodsList", pageBean.getRoot());
				}
			}
			req.getRequestDispatcher("/topSearchGoodsList.jsp").forward(req, resp);
		}
	}

	/**
	 * 从店铺索引中查询店铺的id
	 * 
	 * @author kansum
	 */
	private String queryShopIdsFromIndex(String keyword) throws IOException
	{
		// 获得索引器
		IndexSearcher searcher = SystemToolkit.getIndexSearcher(Final.INDEX_SHOP);
		if (searcher == null)
		{
			return null;
		}

		// 查询的结果放在这里集合
		StringBuffer sids = new StringBuffer();

		// 首先用nick查询店铺
		Term term = new Term("nick", keyword);
		Query query = new TermQuery(term);
		TopDocs topDocs = searcher.search(query, null, 1);
		if (topDocs.totalHits > 0)
		{
			Document doc = searcher.doc(topDocs.scoreDocs[0].doc);
			sids.append(doc.get("sid"));
		}
		// 如果没有nick对应的店铺,用title查询
		else
		{
			term = new Term("title", keyword);
			query = new TermQuery(term);

			// 排序字段
			Sort sort = new Sort(new SortField[]
			{ new SortField("sellerCreditScore", SortField.STRING, true) });
			topDocs = searcher.search(query, null, 10, sort);

			int totalHits = topDocs.totalHits;
			if (totalHits > 0)
			{
				// 搜索返回的结果集合
				ScoreDoc[] hitDocs = topDocs.scoreDocs;

				for (int i = 0; i < totalHits; i++)
				{
					Document doc = searcher.doc(hitDocs[i].doc);
					sids.append(doc.get("sid")).append(",");
				}
			}
			if (sids.length() > 0)
				sids.deleteCharAt(sids.length());
		}

		searcher.close();

		if (sids.length() == 0)
			return null;
		else
			return sids.toString();
	}
}
